package com.ljt.yupictureddd.infrastracture.manager.upload;

import cn.hutool.core.io.FileUtil;
import com.ljt.yupictureddd.infrastracture.exception.BusinessException;
import com.ljt.yupictureddd.infrastracture.exception.ErrorCode;
import com.ljt.yupictureddd.infrastracture.exception.ThrowUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@Service
public class FilePictureUpload extends PictureUploadTemplate {
    /**
     * @param inputSource
     * @param tempFile
     */
    @Override
    protected void processFile(Object inputSource, File tempFile) {
        try {
            ((MultipartFile) inputSource).transferTo(tempFile);
        } catch (IOException e) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }
    }

    /**
     * @param inputSource
     * @return
     */
    @Override
    protected String getOriginalFilename(Object inputSource) {
        return ((MultipartFile) inputSource).getOriginalFilename();
    }

    /**
     * @param inputSource
     */
    @Override
    protected void validatePicture(Object inputSource) {

//        判断空
        MultipartFile multipartFile = (MultipartFile) inputSource;
        ThrowUtils.throwIf(multipartFile == null, ErrorCode.PARAMS_ERROR, "文件为空");
//        判断文件大小
        final long ONE_MB = 1024 * 1024;
        long size = multipartFile.getSize();
        ThrowUtils.throwIf(size > 2 * ONE_MB, ErrorCode.PARAMS_ERROR, "文件大小太大");
//        判断文件类型
        final List<String> fileType = Arrays.asList("png", "gif", "jpg", "webp", "jpeg");
        String suffix = FileUtil.getSuffix(multipartFile.getOriginalFilename());
        ThrowUtils.throwIf(!fileType.contains(suffix), ErrorCode.PARAMS_ERROR, "文件类型不对");

    }
}
